import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;



@ccclass('TimerControl')
export class TimerControl extends Component {
    //为了计时的精准，放在update中执行计时，所以需要挂在常驻节点上
    public IncidentList: Map<string, { type: [Function, number, number, boolean] }> = new Map<string, { type: [Function, number, number, boolean] }>;

    private static _instance: TimerControl = null;
    public static get Instance(): TimerControl {
        if (!this._instance) {
            this._instance = new TimerControl();
        }
        return this._instance;
    }

    protected onLoad(): void {
        TimerControl._instance = this;
    }

    protected update(dt: number): void {
        this.IncidentList.forEach((data, key) => {
            data.type[1] -= dt;
            if (data.type[1] <= 0) {
                data.type[0]();
                if (data.type[3]) {
                    data.type[1] = data.type[2];
                } else {
                    this.ReMoveIncident(key);
                }
            }
        })
    }

    /**
     * 添加定时事件
     * @param IncidentName 添加事件的标识名字
     * @param fun 计时结束后执行的事件
     * @param Time 计时的时长
     * @param isLoop 是否循环执行
     */
    AddIncident(IncidentName: string, fun: Function, Time: number, isLoop: boolean = false) {
        this.IncidentList.set(IncidentName, { type: [fun, Time, Time, isLoop] });
    }
    /**
     * 删除定时事件
     * @param IncidentName 标识名字
     */
    ReMoveIncident(IncidentName: string) {
        this.IncidentList.delete(IncidentName);
    }

}


